﻿/*******************************************************************************
 * AAEngine
 * Copyright (c) 2010 Mike Jarosch
 *
 * Original source PushButton Engine:
 * Copyright (C) 2009 PushButton Labs, LLC
 * For more information see http://www.pushbuttonengine.com
 *
 * This file is licensed under the terms of the MIT license, which is included
 * in the "MIT License.txt" file at the root directory of this SDK.
 ******************************************************************************/

using AAEngine.Engine.Entities;

namespace AAEngine.Engine.Components
{
    /// <summary>
    /// Helper component to group entities.
    /// </summary>
    public class GroupMemberComponent : EntityComponent
    {
        string _groupName;
        GroupManagerComponent _currentManager;

        public GroupManagerComponent GroupManager
        {
            get { return GroupManagerComponent.GetGroupByName(_groupName); }
        }

        public string GroupName
        {
            set
            {
                OnRemove();
                _groupName = value;
                OnAdd();
            }
            get { return _groupName; }
        }

        public override void OnAdd()
        {
            var currentManager = GroupManager;
            if (_currentManager == null && currentManager != null)
            {
                _currentManager = currentManager;
                _currentManager.AddMember(this);
            }
        }

        public override void OnReset()
        {
            OnRemove();
            OnAdd();
        }

        public override void OnRemove()
        {
            if (_currentManager != null)
            {
                _currentManager.RemoveMember(this);
                _currentManager = null;
            }
        }
    }
}
